/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import { BuildDirConst } from '../../const/build-directory-const.js';
import { CompileResourceBuildCommandType } from '../../utils/compile-resources-util.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { AbstractCompileResource } from '../abstract/abstract-compile-resource.js';
import { TaskNames } from '../common/task-names.js';
import { ModuleTargetData } from '../data/hap-task-target-data.js';
import { TargetTaskService } from '../service/target-task-service.js';

import { getTaskRealName } from './hook/legacy-hook-compile-resource.js';
import LegacyFATask = TaskNames.LegacyFATask;
import { HarTargetUtil } from '../../utils/har-target-util.js';
import { ModuleTaskService } from '../service/module-task-service.js';

/**
 * 老模型的Preview适配Restool资源增量编译任务
 *
 * @since 2022/1/20
 */
export class LegacyPreviewCompileResource extends AbstractCompileResource {
  protected processProfileTask: string;
  private _log: OhosLogger = OhosLogger.getLogger(LegacyPreviewCompileResource.name);

  declareExecutionCommand(): string {
    return this.compileCommands!.toString();
  }

  constructor(taskService: TargetTaskService, entryModuleName?: string) {
    super(taskService, getTaskRealName(LegacyFATask.PREVIEW_COMPILE_RESOURCE, entryModuleName));
    this.entryModuleName = entryModuleName;
    this.generateSourceRDir = this.getTaskTempDir(this.targetData, BuildDirConst.R, false);
    this.processProfileTask = getTaskRealName(LegacyFATask.PREVIEW_PROCESS_RESOURCE, this.entryModuleName).name;
  }

  initTaskDepends() {
    const relatedEntryModules = this.service.getRelatedEntryModules();
    const moduleType = this.service.getModuleModel().getModuleType();
    if (ModuleTaskService.checkEntryModules(moduleType, relatedEntryModules)) {
      for (const entryName of relatedEntryModules!) {
        this.declareDepends(getTaskRealName(LegacyFATask.PREVIEW_PROCESS_RESOURCE, entryName).name);
      }
    } else {
      this.declareDepends(getTaskRealName(LegacyFATask.PREVIEW_PROCESS_RESOURCE).name);
    }
  }

  protected initHarModuleDepends() {
    const depHarTargets = HarTargetUtil.calDepHarTargets(this.targetService);
    depHarTargets.forEach((targetName, harName) => this.declareDepends(`${targetName}@${LegacyFATask.PREVIEW_COMPILE_RESOURCE.name}`, harName));
  }

  async doTaskAction(): Promise<void> {
    await this.compilationProcess(CompileResourceBuildCommandType.COMMAND, this.targetData);
  }

  async invokeRestool(targetData: ModuleTargetData) {
    await this.previewCompileLink(this._log, async () => {
      if (this.entryModuleName !== undefined) {
        await this.retainDeviceType(targetData, this.entryModuleName!, this._log);
      }
    });
  }
}
